import { asyncRoutes, constantRoutes } from '@/router';

/**
 * 通过meta.access判断是否与当前用户权限匹配
 * @param accessList
 * @param route
 */
function hasPermission(accessList, route) {
  if (route.meta && route.meta.access) {
    return accessList.some(access => route.meta.access.includes(access));
  } else {
    return true;
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, accessList) {
  const res = [];

  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(accessList, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, accessList);
      }
      res.push(tmp);
    }
  });

  return res;
}

const permission = {
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = constantRoutes.concat(routes);
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { accessList } = data;
        const accessedRoutes = filterAsyncRoutes(asyncRoutes, accessList);
        commit('SET_ROUTES', accessedRoutes);
        resolve(accessedRoutes);
      });
    }
  }
};

export default permission;
